<script setup lang="ts">
import { ref, unref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useRouter } from 'vue-router'
import { saveDataApi } from '@/api/attachment'
import { useEventBus } from '@/hooks/event/useEventBus'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import Write from './components/Write.vue'

const { emit } = useEventBus()

const { push, go } = useRouter()

const { t } = useI18n()

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()

  if (formData) {
    // 过滤掉空值或null，但保留0
    const filteredData = Object.fromEntries(
      Object.entries(formData).filter(([key, value]) => {
        return value !== '' && value !== null && value !== undefined
      })
    )

    loading.value = true
    const res = await saveDataApi(filteredData)
      .catch(() => {})
      .finally(() => {
        loading.value = false
      })
    if (res) {
      emit('getList', 'add')
      push('/product/attachment-management')
    }
  }
}
</script>

<template>
  <ContentDetailWrap
    :title="t('attachment.add')"
    @back="push('/attachment-module/attachment/page')"
  >
    <Write ref="writeRef" :index="1" />

    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :loading="loading" @click="save"
        >{{ t('action.save') }}
      </BaseButton>
    </template>
  </ContentDetailWrap>
</template>
@/hooks/event/useEventBus
